import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/base_components/base_appointment_time.dart';
import 'package:x3_component_core/components/base_components/list_view_single_choice_component.dart';
import 'package:x3_component_core/components/date_components/base_select_query_date.dart';
import 'package:x3_component_core/components/dialog_components/base_dialog_component.dart';
import 'package:x3_component_core/components/dialog_components/base_image_video_picker.dart';
import 'package:x3_component_core/components/dialog_components/base_picker.dart';
import 'package:x3_component_core/components/state_components/base_loading_component.dart';
import 'package:x3_component_core/components/selector_components/selector_template/base_bottom_sheet_template.dart';
import 'package:flutter_holo_date_picker/flutter_holo_date_picker.dart';

class BaseComponentUtils {
  BaseComponentUtils._();

  /// 构建ListView每个item间的向右的箭头
  static Widget buildListViewRightIcon(BuildContext context) {
    return Container(margin: EdgeInsets.only(left: 2), child: Icon(BaseIconData.x3RightArrow, color: BaseBodyTheme.iconColor, size: 12));
  }

  /// 构建竖直方向的分割线
  static Widget buildVerticalDivider() {
    return VerticalDivider(width: 1);
  }

  /// 构建水平方向的分割线
  static Widget buildHorizontalDivider() {
    return Divider(height: 1);
  }

  /// 构建label value形式的row组件（ 数量: 1 ）
  static Widget buildTextSpanWidget(List<String> spans, {Map<int, TextStyle> styles, int maxLines = 10, double spanWidth = 4.0, bool isInterval = true}) {
    String value = spans[0];
    spans.removeAt(0);
    return Text.rich(
      TextSpan(
        text: value,
        style: styles == null ? null : styles[0] ?? null,
        children: spans.asMap().keys.map((int index) {
          return TextSpan(children: [
            if (isInterval) WidgetSpan(child: SizedBox(width: spanWidth)),
            TextSpan(text: spans[index], style: styles == null ? null : styles[index + 1] ?? null),
          ]);
        }).toList(),
      ),
      maxLines: maxLines,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 构建label value形式的一行row组件(分割部分在中间，eg：aaa... bbb)
  static Widget buildTextSpanFlexible({@required String title, @required String subTitle, Map<int, TextStyle> styles}) {
    TextStyle titleTextStyle = styles == null ? null : styles[0] ?? null;
    TextStyle subTitleTextStyle = styles == null ? null : styles[1] ?? null;
    return Row(
      children: [
        Flexible(child: Text(title, style: titleTextStyle, maxLines: 1, overflow: TextOverflow.ellipsis)),
        Text(subTitle, style: subTitleTextStyle),
      ],
    );
  }

  static Widget buildTextSpanExpanded({@required String title, @required String subTitle, Map<int, TextStyle> styles}) {
    TextStyle titleTextStyle = styles == null ? null : styles[0] ?? null;
    TextStyle subTitleTextStyle = styles == null ? null : styles[1] ?? null;
    return Row(
      children: [
        Expanded(child: Text(title, style: titleTextStyle, maxLines: 1, overflow: TextOverflow.ellipsis)),
        SizedBox(width: 12),
        Text(subTitle, style: subTitleTextStyle),
      ],
    );
  }

  /// 构建容器底部阴影
  static List<BoxShadow> buildBoxShadow() {
    return [BoxShadow(offset: Offset(1, 2), color: Colors.grey[300], blurRadius: 2)];
  }

  /// 下方弹出 空白控件
  static buildBottomSheet(BuildContext buildContext, {Widget child, Color backgroundColor = Colors.white, double height}) {
    showModalBottomSheet(
      isScrollControlled: height == null ? false : true,
      context: buildContext,
      backgroundColor: backgroundColor,
      elevation: 10,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10))),
      builder: (context) {
        return Container(width: double.infinity, height: height, child: child ?? SizedBox());
      },
    );
  }

  /// 下方弹出默认模板控件
  static buildDefaultBottomSheet(BuildContext buildContext, {Widget child, String hit, Widget footerWidget, bool hiddenHeaderWidget = false, double height, Color backgroundColor = Colors.white, EdgeInsets contentPadding = const EdgeInsets.only(left: 16, right: 16, bottom: 8), bool enableDrag = true}) {
    showModalBottomSheet(
      isScrollControlled: height == null ? false : true,
      context: buildContext,
      backgroundColor: backgroundColor,
      enableDrag: enableDrag,
      elevation: 10,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10))),
      builder: (context) {
        return BaseDefaultBottomSheetTemplate(child: child, footerWidget: footerWidget, hit: hit, hiddenHeaderWidget: hiddenHeaderWidget, contentPadding: contentPadding, height: height);
      },
    );
  }

  /// 列表选择的底部弹框   -- 单选
  static showBottomSheetListViewSingleChoice({@required BuildContext context, String hit = '请选择', @required List<BaseKeyValueModel> items, BaseKeyValueModel selectedItem, double itemExtent = 49.0, Widget Function(BuildContext context, int index, BaseKeyValueModel item) itemBuilder, @required Function(BaseKeyValueModel selected) selectedEvent, bool itemShowKey = false}) {
    BaseComponentUtils.buildDefaultBottomSheet(
      context,
      hit: hit,
      child: ListViewSingleChoiceComponent(
        items: items,
        itemExtent: itemExtent,
        selectedItem: selectedItem,
        itemBuilder: itemBuilder,
        selectedEvent: selectedEvent,
        itemShowKey: itemShowKey,
      ),
    );
  }

  /// 弹出对话框
  static Future<Null> showCommonDialog(BuildContext context, {String title, Widget titleWidget, String content, Widget contentWidget, Function onOKPress, Function onCancelPress}) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return BaseDialogComponent(
          title: title,
          titleWidget: titleWidget,
          content: content,
          contentWidget: contentWidget,
          onOKPress: onOKPress,
          onCancelPress: onCancelPress,
        );
      },
    );
  }

  /// 弹出消息对话框
  static Future<Null> showMessageDialog(BuildContext context, {String content, Widget contentWidget, @required VoidCallback onOKPress}) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return BaseDialogComponent(content: content, contentWidget: contentWidget, onOKPress: onOKPress);
      },
    );
  }

  /// 日期范围选择器
  static Future<DateTimeRange> openDateRangePicker(BuildContext context, {DateTimeRange initialDateRange, DateTime currentDate}) {
    return showDateRangePicker(
      context: context,
      initialDateRange: initialDateRange,
      currentDate: currentDate,
      firstDate: DateTime(1940),
      lastDate: DateTime(DateTime.now().year + 10),
      builder: (context, child) => Theme(
          data: ThemeData.light().copyWith(
              colorScheme: ThemeData.light().colorScheme.copyWith(
                    primary: Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor,
                  )),
          child: child),
    );
  }

  /// 日期选择
  static Future<void> openDatePicker(BuildContext context, {DateTime firstDate, DateTime currentDate, Function(DateTime dateTime) onDateChanged}) async {
    DateTime initialDate = currentDate ?? new DateTime.now();
    DateTime firstDateTime = firstDate ?? new DateTime(1700);

    var dateTime = await DatePicker.showSimpleDatePicker(
      context,
      titleText: '选择日期',
      firstDate: firstDateTime,
      lastDate: new DateTime(3000),
      dateFormat: 'yyyy-MMM-dd',
      initialDate: initialDate.toLocal(),
      locale: DateTimePickerLocale.zh_cn,
      textColor: Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor,
      backgroundColor: Colors.white,
      confirmText: '确定',
      cancelText: '取消'
    );
    onDateChanged(dateTime);
    // showDialog(
    //     context: context,
    //     builder: (context) {
    //       return Theme(
    //         data: ThemeData().copyWith(
    //             colorScheme: ThemeData().colorScheme.copyWith(
    //                   primary: Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor,
    //                 )),
    //         child: Dialog(
    //           child: DatePickerWidget(
    //             firstDate: firstDate,
    //             lastDate: new DateTime(3000),
    //             initialDate: initialDate,
    //             locale: DateTimePickerLocale.zh_cn,
    //             onConfirm: ((DateTime date, list) {
    //               onDateChanged(date);
    //               Navigator.of(context).pop();
    //             }),
    //           ),
    //           // child: CalendarDatePicker(
    //           //     initialDate: initialDate,
    //           //     firstDate: firstDateTime,
    //           //     lastDate: new DateTime(3000),
    //           //     onDateChanged: (DateTime dateTime) {
    //           //       onDateChanged(dateTime);
    //           //       Navigator.of(context).pop();
    //           //     }),
    //         ),
    //       );
    //     });
  }

  /// 选择查询日期
  static void openSelectQueryDate(BuildContext context, {@required Function(DateTime start, DateTime end) onDateChanged, DateTime defaultStart, DateTime defaultEnd}) {
    showDialog(
        context: context,
        barrierColor: Colors.transparent,
        builder: (context) {
          return BaseSelectQueryDate(selectDate: onDateChanged, startDateTime: defaultStart, endDateTime: defaultEnd);
        });
  }

  /// 选择预约时间
  static void openSelectAppointmentTime(BuildContext context, {String hit = "请选择", String appointmentArea, DateTime appointmentTime, String logisticsCode, Function(DateTime, String) onChange}) {
    BaseComponentUtils.buildDefaultBottomSheet(
      context,
      height: MediaQuery.of(context).size.height * 3 / 5,
      hit: hit,
      child: BaseAppointmentTime(appointmentTime: appointmentTime, appointmentArea: appointmentArea, logisticsCode: logisticsCode, onChange: onChange),
    );
  }

  /// 打开选择图片和视频的底部弹出框
  static void openImageVideoPicker(BuildContext context, Function(List<dynamic> assets) getPickerAssets, {bool showImagePicker = true, bool showVideoPicker = false, int maxAssetsForAssetsForGallery = 9}) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext bottomContext) => BaseImageVideoPicker(widgetContext: context, showImagePicker: showImagePicker, showVideoPicker: showVideoPicker, getPickerAssets: getPickerAssets, maxAssetsForAssetsForGallery: maxAssetsForAssetsForGallery),
    );
  }

  /// 打开选择资源的底部弹出框
  static void openPicker(BuildContext context, Function(List<dynamic> assets) getPickerAssets, {bool showImagePicker = true, bool showVideoPicker = false, bool showFilePicker = false, int maxAssetsForAssetsForGallery = 9, Function(BaseKeyValueModel typeModel) getPickerAssetsType, bool splitPaths = false}) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext bottomContext) => BasePicker(widgetContext: context, showImagePicker: showImagePicker, showVideoPicker: showVideoPicker, showFilePicker: showFilePicker, getPickerAssets: getPickerAssets, splitPaths: splitPaths, getPickerAssetsType: getPickerAssetsType, maxAssetsForAssetsForGallery: maxAssetsForAssetsForGallery),
    );
  }

  /// 显示加载进度条
  static Future<Null> showLoadingDialog(BuildContext context, {String hint}) {
    return showDialog(context: context, builder: (BuildContext context) => BaseLoadingComponent(hint: hint));
  }

  /// 关闭进度条
  static void hideLoadingDialog(BuildContext context) {
    Navigator.of(context, rootNavigator: true).pop();
  }
}
